/*
 * Systemprogrammierung
 * Multiplayer-Quiz
 *
 * Server
 *
 * user.c: Implementierung der User-Verwaltung
 */

#include <stdlib.h>
#include <string.h>
#include "user.h"
#include <stdint.h>

struct UserInfo *oUserList;

// Returns the number of logged in users
int user_GetUserCount() {
	int i;
	struct UserInfo *oTempUserInfo;

	i = 0;
	oTempUserInfo = oUserList;
	while (1) {
		if (oTempUserInfo == NULL) {
			return i;
		}
		else {
			oTempUserInfo = oTempUserInfo -> ptrNext;
			i++;
		}
	}

	return 0;
}

// Returns 0 for not taken and 1 for already taken
int user_UsernameAlreadyTaken(char *sUsername) {
	struct UserInfo *oTempUserInfo;

	oTempUserInfo = oUserList;
	while (1) {
		if (oTempUserInfo == NULL) {
			return 0;
		}
		else {
			if (strcmp(oTempUserInfo -> sUsername, sUsername) == 0) { return 1; }
			oTempUserInfo = oTempUserInfo -> ptrNext;
		}
	}

	return 0;
}

int user_UserIDAlreadyInUse(uint8_t iUserID) {
	struct UserInfo *oTempUserInfo;

	oTempUserInfo = oUserList;
	while (1) {
		if (oTempUserInfo == NULL) {
			return 0;
		}
		else {
			if (oTempUserInfo -> iUserID == iUserID) { return 1; }
			oTempUserInfo = oTempUserInfo -> ptrNext;
		}
	}

	return 0;
}

// Returns a free User-ID, returns -1 if no free ID is available
int16_t user_GetFreeUserID() {
	int16_t iNewUserID;

	for (iNewUserID = 0; iNewUserID < 255; iNewUserID++) {
		if (user_UserIDAlreadyInUse(iNewUserID) == 0) { return iNewUserID; }
	}
	if (user_UserIDAlreadyInUse((int16_t)255) == 0) { return (int16_t)255; }
	return -1;
}

int user_AddNewUser(char *sUsername, int iSocket) {
	struct UserInfo *oTempUserInfo;
	struct UserInfo oNewUserInfo;
	int16_t iUserID;

	if (user_GetUserCount() > 5) { return -1; }
	iUserID = user_GetFreeUserID();
	if (iUserID == (int16_t)-1) { return -1; }

	oNewUserInfo.sUsername = sUsername;
	oNewUserInfo.iUserID = (uint8_t)iUserID;
	oNewUserInfo.iSocket = iSocket;
	oNewUserInfo.iPunktestand = 0;
	oNewUserInfo.bEndphaseAktiv = 0;


	oTempUserInfo = oUserList;
	while (1) {
		if (oTempUserInfo == NULL) {
			oTempUserInfo = &oNewUserInfo;
			return (int)iUserID;
		}
		else {
			oTempUserInfo = oTempUserInfo -> ptrNext;
		}
	}

	return -1;
}

void user_ReOrderByScore() {


	return;
}
